package manager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;

import manager.interfaces.IOrderManager;
import view.MyDialog;
import vo.Order;

public class OrderManager implements IOrderManager {

	private static OrderManager orderManager = new OrderManager();
	private HashMap<Integer, ArrayList<Order>> ordersList;
	private HashMap<Integer, Boolean> cuponList;
	
	private OrderManager() { 
		ordersList = new HashMap<Integer, ArrayList<Order>>();
		cuponList = new HashMap<Integer, Boolean>();
	}
	
	public static OrderManager getInstance() {
		
		if(null == orderManager) {
			return new OrderManager();
		} else {
			return orderManager;
		}		
	}
	
	@Override
	public void createOrder(int customerId, Order order) {
	
		ArrayList<Order> orders = ordersList.get(customerId);
		
		if(null == orders) {
			orders = new ArrayList<Order>();
		}
		// 고객번호로 주문 목록을 찾은 후 추가
		orders.add(order);
		
		// 해쉬 테이블에 주문 추가
		ordersList.put(customerId, orders);
		
		// 쿠폰 발행 여부 수행
		giveCupon(customerId);
	}

	@Override
	public Date displayDate() {
		// TODO Auto-generated method stub
		Calendar cal = Calendar.getInstance();
		
		return cal.getTime();
	}

	@Override
	public void giveCupon(int customerId) {
						
		ArrayList<Order> orders = ordersList.get(customerId);
		
		if(orders != null){
			// 주문 내역이 3개인 경우 쿠폰 리스트에 기록
			if((orders.size() % 3) == 0) {

				// 고객번호를 순회하면서
				Iterator iterator = cuponList.keySet().iterator();
				
				while(iterator.hasNext()) {
					
					boolean checkCupon = cuponList.get(iterator.next());
					
					// 쿠폰 발행대상인 경우
					if(checkCupon) {
						new MyDialog().sendMsg(checkCupon, customerId + "고객님께 무료쿠폰 발송");		
								
					}		
				}
			} 		
		}		
	}
	
	public int getOrderedMenuCount(String menuName) {
		
		int orderCount = 0;
		
		// 고객번호를 순회하면서
		Iterator iterator = ordersList.keySet().iterator();
		
		while(iterator.hasNext()) {
			
			ArrayList<Order> orders = ordersList.get(iterator.next());
			
			for(int i = 0; i < orders.size(); ++i) {
			
				Order order = orders.get(i);
				ArrayList<String> menus = order.getOrderMenu();
				
				if(menus.contains(menuName)){
					++orderCount;
				}
				
			}
			
		}
				
		return orderCount;
	}

}
